package com.example.getroot;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.FileUtils;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RootHelper {

    public static final String FILE_NAME = "bili_root_test";

    private Context mContext;

    public RootHelper(Context context) {
        mContext = context;
    }

    private void prepareLogDirectory() {
        String path = "/sdcard/rh";
        File f = new File(path);
        if (!f.exists()) {
            f.mkdir();
        }
    }


    public void prepare() {

        prepareLogDirectory();

        byte[] buffer = new byte[1024 * 32];

        InputStream is = null;
        FileOutputStream fo = null;


        try {
            AssetManager am = mContext.getAssets();
            is = am.open(FILE_NAME);

            prepareSoLibFile();
            fo = new FileOutputStream(new File(getFile()));

            while (true) {
                int readed = is.read(buffer);

                if (0 < readed) {
                    fo.write(buffer, 0, readed);
                } else {
                    break;
                }
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (fo != null) {
                try {
                    fo.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        buffer = null;
    }

    private void prepareSoLibDir() {
        File file = new File(getRootPath() +LIB);
        file.mkdirs();
    }

    private void prepareSoLibFile() {
        prepareSoLibDir();

        String file = getFile();
        Log.e("root", file);
        try {
            final File rootFile = new File(file);
            if (rootFile != null) {
                rootFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private final static String SO = "libperml.so";


    private final static String LIB = "libs";


    public String getFile() {
        if (!mContext.getFilesDir().exists()) {
            mContext.getFilesDir().mkdir();
        }

        return getRootPath() +LIB + File.separator + SO;

//		File f = new File(mContext.getFilesDir().getAbsolutePath() + "/bili_root_test");
//		if (f.exists()) {
//			f.delete();
//		}
//		
//		
//		return mContext.getFilesDir().getAbsolutePath() + "/bili_root_test";
    }

    @NonNull
    private String getRootPath() {
        return "/data/data/com.example.getroot/";
    }


    public String exePath(String param) {
        prepare();

        String binPath = getFile();

        String s = "\n";

        Log.d("rhx", "" + binPath);

        try

        {

            String[] args = new String[4];
            args[0] = binPath;                      // program name
            args[1] = android.os.Process.myUid() + "";   // 1st param: user id of calling process
            args[2] = MainApplication.getInst().getPackageName();          // 2nd param: package name
            args[3] = "rksvc";

            FileUtils.setPermissions(getRootPath()+LIB,0755,-1,-1);
            int value = FileUtils.setPermissions(binPath, 0755, -1, -1); // drwxrwxr-x

            Process p = Runtime.getRuntime().exec(binPath);
            p.waitFor();
            Log.d("rhx", "process exit=" + p.exitValue());
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    p.getErrorStream()));


            String line = null;
            while ((line = in.readLine()) != null) {
                s += line + "\n";
            }

            Log.d("rhx", "xx " + s);

        } catch (IOException e) {
            e.printStackTrace();
            return s;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return s;
        }

        return s;
    }

}
